const AlphaVantageService = require('./AlphaVantageService');
const TencentStockService = require('./TencentStockService');
const SinaStockService = require('./SinaStockService');
const DatabaseService = require('./DatabaseService');
// 移除对 StrategyService 的引用以避免循环依赖

class StockHistoryService {
  // 获取并存储股票历史数据
  static async fetchAndStoreHistory(symbol, interval = 'daily') {
    try {
      // 首先尝试从AlphaVantage获取历史数据
      console.log(`Fetching historical data for ${symbol} from Alpha Vantage...`);
      const historicalData = await AlphaVantageService.getHistoricalData(symbol, interval);
      
      // 存储到数据库
      console.log(`Storing ${historicalData.length} records for ${symbol} to database...`);
      await DatabaseService.saveStockHistory(symbol, historicalData);
      
      console.log(`Successfully fetched and stored ${historicalData.length} records for ${symbol} from Alpha Vantage`);
      return historicalData;
    } catch (alphaError) {
      console.error(`Failed to fetch from Alpha Vantage for ${symbol}: ${alphaError.message}`);
      
      // 如果Alpha Vantage失败，尝试从腾讯获取历史数据
      try {
        console.log(`Trying to fetch historical data for ${symbol} from Tencent...`);
        const historicalData = await TencentStockService.getHistoricalData(symbol, interval);
        
        // 存储到数据库
        console.log(`Storing ${historicalData.length} records for ${symbol} to database...`);
        await DatabaseService.saveStockHistory(symbol, historicalData);
        
        console.log(`Successfully fetched and stored ${historicalData.length} records for ${symbol} from Tencent`);
        return historicalData;
      } catch (tencentError) {
        console.error(`Failed to fetch from Tencent for ${symbol}: ${tencentError.message}`);
        
        // 如果腾讯也失败，尝试从新浪获取历史数据
        try {
          console.log(`Trying to fetch historical data for ${symbol} from Sina...`);
          const historicalData = await SinaStockService.getHistoricalData(symbol, interval);
          
          // 存储到数据库
          console.log(`Storing ${historicalData.length} records for ${symbol} to database...`);
          await DatabaseService.saveStockHistory(symbol, historicalData);
          
          console.log(`Successfully fetched and stored ${historicalData.length} records for ${symbol} from Sina`);
          return historicalData;
        } catch (sinaError) {
          console.error(`Failed to fetch from Sina for ${symbol}: ${sinaError.message}`);
          // 如果所有服务都失败，抛出错误
          throw new Error(`Failed to fetch data from Alpha Vantage, Tencent, and Sina: ${sinaError.message}`);
        }
      }
    }
  }

  // 从数据库获取历史数据
  static async getHistoryFromDatabase(symbol, limit = 100) {
    try {
      const historyData = await DatabaseService.getStockHistory(symbol, limit);
      return historyData;
    } catch (error) {
      console.error(`Failed to get history from database for ${symbol}: ${error.message}`);
      console.error(error.stack); // 添加堆栈跟踪
      throw new Error(`Failed to get history from database for ${symbol}: ${error.message}`);
    }
  }

  // 从数据库获取指定日期范围的历史数据
  static async getHistoryByDateRange(symbol, startDate, endDate) {
    try {
      const historyData = await DatabaseService.getStockHistoryByDateRange(symbol, startDate, endDate);
      return historyData;
    } catch (error) {
      console.error(`Failed to get history by date range from database for ${symbol}: ${error.message}`);
      console.error(error.stack); // 添加堆栈跟踪
      throw new Error(`Failed to get history by date range from database for ${symbol}: ${error.message}`);
    }
  }

  // 获取历史数据（优先从数据库获取，如果没有则从API获取并存储）
  static async getHistoricalData(symbol, interval = 'daily', limit = 100) {
    try {
      // 首先尝试从数据库获取
      console.log(`Checking database for history data of ${symbol}...`);
      let historyData = await this.getHistoryFromDatabase(symbol, limit);
      
      // 如果数据库中没有数据，则从API获取并存储
      if (historyData.length === 0) {
        console.log(`No data found in database for ${symbol}, fetching from API...`);
        historyData = await this.fetchAndStoreHistory(symbol, interval);
        
        // 只返回请求的数量
        if (historyData.length > limit) {
          historyData = historyData.slice(-limit);
        }
      } else {
        console.log(`Found ${historyData.length} records in database for ${symbol}`);
      }
      
      // 按日期排序
      historyData.sort((a, b) => new Date(a.date) - new Date(b.date));
      
      return historyData;
    } catch (error) {
      console.error(`Error getting historical data for ${symbol}: ${error.message}`);
      console.error(error.stack); // 添加堆栈跟踪
      // 如果获取真实数据失败，直接抛出错误而不是使用模拟数据
      throw new Error(`Failed to fetch real data for ${symbol}: ${error.message}`);
    }
  }
}

module.exports = StockHistoryService;